package net.wanho.service.impl;

import com.aliyun.oss.OSSClient;
import lombok.SneakyThrows;
import net.wanho.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Value("${file.stail}")
    private String stail;
    @Value("${file.path}")
    private String filePath;
    @Value("${file.urls}")
    private String urls;
    @Resource
    private OSSClient ossClient;

    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucket;

    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;
    @Override
    public String upload(String originalFilename, InputStream inputStream) {
        String dir = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); // 文件夹名
        String filename =dir + "/" + UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
        ossClient.putObject(bucket, filename,inputStream); // 上传文件
        String url = "http://" + bucket + "." + endpoint + "/" + filename;
        return url;
    }

    @SneakyThrows
    @Override
    public String uploadFile(MultipartFile file) {
        //拼接文件路径
        String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String filename = file.getOriginalFilename();
        filename =UUID.randomUUID()+filename.substring(filename.lastIndexOf("."));
        File uploadPath=new File(filePath+ File.separator+format+File.separator+filename);
        if (!uploadPath.getParentFile().exists()) {
            uploadPath.getParentFile().mkdirs();
        }
        file.transferTo(uploadPath);
        String url = urls+stail+ format + "/" + filename;
        return url;
    }
}
